<template>
  <div class="slave-main">
    <el-dialog
      :title="machine.title"
      :visible.sync="machine.visible"
      width="78%"
      height="600px"
      top="30px"
      @close="closeSlaveDialog(1)"
    >
      <div class="slave-main dialog-main">
        <div class="filter-container">

          <el-dropdown v-if="machine.group_id === 1" @command="batchHandle">
            <el-button type="danger" size="medium">
              批量操作<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="cancelManager">取消管理</el-dropdown-item>
              <el-dropdown-item command="addManager">添加管理</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button
            v-if="machine.group_id !== 1"
            class="filter-item"
            :type="inSlave"
            icon="el-icon-edit"
            size="medium"
            @click="getDataSlaveInfo()"
          >管理执行机</el-button>

          <el-button
            v-if="machine.group_id !== 1"
            class="filter-item slave-button"
            :type="notInSlave"
            icon="el-icon-plus"
            size="medium"
            @click="listNotInGroup()"
          >新增执行机</el-button>

          <el-button
            id="notInSlave"
            class="filter-item export"
            type="primary"
            icon="el-icon-download"
            size="medium"
            @click="exportExcelHandle()"
          >导出</el-button>

        </div>
        <el-table
          border
          max-height="300"
          highlight-current-row
          :data="pageDataMachine"
          style="width: 100%"
          @selection-change="selectRowHandle"
          @sort-change="tableSortChange"
        >
          <el-table-column type="selection" align="center" width="55" />
          <!--          <el-table-column-->
          <!--            prop="id"-->
          <!--            label="ID"-->
          <!--            align="left"-->
          <!--            width="180"-->
          <!--          />-->
          <el-table-column prop="slave_name" align="center" label="节点名称" min-width="200" sortable />
          <el-table-column prop="ip" align="center" min-width="130" label="IP" sortable />
          <el-table-column
            prop="user_name"
            align="center"
            min-width="100"
            :show-overflow-tooltip="true"
            label="用户名"
            sortable
          />
          <el-table-column prop="parallel_max" align="center" label="最大线程" width="110" sortable />
          <el-table-column prop="parallel_now" align="center" label="当前线程" width="110" sortable />
          <el-table-column prop="status" align="center" label="状态" sortable />
          <el-table-column prop="work_path" align="center" label="工作目录" width="110" sortable />
          <el-table-column prop="mark" align="center" min-width="180" label="备注" sortable />
          <el-table-column
            label="操作"
            fixed="right"
            header-align="center"
            align="center"
            min-width="140"
          >
            <template slot-scope="scope">
              <div v-if="machine.mode === 1">
                <el-button type="text" size="small" @click="editSlaveHandle(scope.row,0)">新增</el-button>
              </div>
              <div v-if="machine.mode === 0">
                <el-button type="text" size="small" @click="editSlaveHandle(scope.row,1)">编辑</el-button>
                <el-button type="text" size="small" @click="editSlaveHandle(scope.row,2)">删除</el-button>
                <el-button type="text" size="small" @click="editSlaveHandle(scope.row,3)">断开</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="pageIndex"
            :page-sizes="[10, 15, 30, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalMachine"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>

    <el-dialog :title="slave.textMap[slave.status]" :visible.sync="slave.visible" top="30px" width="500px">
      <div class="dialog-main">
        <el-form ref="dataForm" :rules="slave.rules" :model="slave.temp" label-position="left" label-width="140px">
          <el-form-item label="节点名称: :" prop="slave_name" class="slave-label-name" required>
            <el-input v-model="slave.temp.slave_name" class="input-countent group-name" />
          </el-form-item>
          <el-form-item label="IP:" prop="mark" class="slave-label-name " aria-disabled="">
            <el-input v-model="slave.temp.ip" class="input-countent" />
          </el-form-item>
          <el-form-item label="最大执行线程:" prop="parallel_now" class="slave-label-name " required>
            <el-input v-model="slave.temp.parallel_max" class="parallel_max" />
          </el-form-item>
          <el-form-item label="当前执行执行线程:" prop="parallel_now" class="slave-label-name" required>
            <el-input v-model="slave.temp.parallel_now" class="input-countent" />
          </el-form-item>
          <el-form-item label="工作状态:" prop="work_path" class="slave-label-name ">
            <el-input v-model="slave.temp.status" class="input-countent" />
          </el-form-item>
          <el-form-item label="工作目录:" prop="work_path" class="slave-label-name " required>
            <el-input v-model="slave.temp.work_path" class="input-countent" />
          </el-form-item>
          <el-form-item label="备注:" prop="mark" class="slave-label-name">
            <el-input
              v-model="slave.temp.mark"
              :autosize="{ minRows: 4, maxRows: 8}"
              type="textarea"
              placeholder="输入备注"
              class="input-countent"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer  btn">
          <el-button class="foot-button" @click="slave.visible = false">
            取消
          </el-button>
          <el-button type="primary" class="foot-button btn" @click="editSlave()">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlaveInfo, listNotInGroupSlave, addSlave, delSlave, breakSlave, editSlaveInfo,
  delExecutor, addExecutor } from '@/api/machine-group'
import { exportExcel1 } from '@/utils/exportExcelUtils'

export default {
  name: 'Slave',
  props: {
    machineListItem: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      tableData: [],
      selectIds: [],
      filtertableData: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      machine: {
        visible: false,
        status: '',
        group_id: '',
        title: '执行机管理',
        textMap: {
          create: '执行机管理'
        },
        mode: 0 // 按钮控制
      },
      // 执行列表编辑弹出框
      slave: {
        visible: false,
        status: '',
        slave_id: '',
        textMap: {
          show: '编辑执行机信息'
        },
        mode: 0, // 按钮控制
        temp: {
          id: '',
          slave_name: '',
          parallel_now: '',
          ip: '',
          work_path: '',
          parallel_max: '',
          mark: ''
        },
        rules: {
          slave_name: [{ required: true, message: '请输入节点名', trigger: 'change' }],
          parallel_now: [{ required: true, message: '当前线程数', trigger: 'change' }],
          parallel_max: [{ required: true, message: '最大线程数', trigger: 'change' }],
          work_path: [{ required: true, message: '工作目录', trigger: 'change' }]
        }
      },
      inSlave: '',
      notInSlave: ''

    }
  },
  computed: {
    // 总数
    totalMachine() {
      return this.tableData.length
    },
    // 当前分页数据
    pageDataMachine() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }
  },
  mounted() {
    this.machine.group_id = this.machineListItem.group_id
    this.machine.mode = 0
    this.machine.visible = true
    this.machine.title = this.machineListItem.group_name + ' - 执行机管理'
    this.listSlaveTable()
  },
  methods: {
    closeSlaveDialog(flag) {
      this.showDialog = false
      this.$emit('closeSlaveDialog', flag)
    },
    selectRowHandle(selection) {
      this.selectIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectIds.push(row.id)
      })
    },
    handleFilterMachine() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = data
    },
    tableSortChange({ column, prop, order }) {
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    listSlaveTable() {
      const params = {
        group_id: this.machineListItem.group_id
      }
      this.inSlave = 'primary'
      this.notInSlave = ''
      listSlaveInfo(params).then(response => {
        this.tableData = response.data
        this.handleFilterMachine()
      })
    },
    listNotInGroup() {
      const params = {
        group_id: this.machine.group_id
      }
      this.machine.mode = 1
      this.inSlave = ''
      this.notInSlave = 'primary'
      listNotInGroupSlave(params).then(response => {
        this.tableData = response.data
        this.handleFilterMachine()
      })
    },
    getDataSlaveInfo() {
      const params = {
        group_id: this.machine.group_id
      }
      this.machine.mode = 0
      this.inSlave = 'primary'
      this.notInSlave = ''
      listSlaveInfo(params).then(response => {
        this.tableData = response.data
        this.handleFilterMachine()
      })
    },
    editSlaveHandle(row, state) {
      if (row.id === '' || row.id === undefined) {
        this.$message.error('未获取执行机id')
        return
      }
      if (state === 0) {
        this.addSlaveHandle(row)
      } else if (state === 2) {
        this.deleteSlaveHandle(row)
      } else if (state === 3) {
        this.breakSlaveHandle(row)
      } else {
        this.updateSlaveHandle(row)
      }
    },
    // 添加执行机到该组
    addSlaveHandle(row) {
      const data = [row.id]
      this.$confirm('确定添加此执行机到执行组中吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        addSlave(data, this.machine.group_id).then(response => {
          this.listNotInGroup()
        })
      })
    },

    // 从改组中删除此执行机
    deleteSlaveHandle(row) {
      const data = [row.id]
      this.$confirm('确定要从执行组中删除此执行机?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delSlave(data, this.machine.group_id).then(response => {
          this.getDataSlaveInfo()
          this.$message.success('删除此执行机成功')
        })
      })
    },
    // 断开执行机链接
    breakSlaveHandle(row) {
      const params = {
        slaveId: row.id
      }
      this.$confirm('确认断开该执行机的连接吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        breakSlave(params).then(response => {
          this.getDataSlaveInfo()
          this.$message.success('断开此执行机成功')
        })
      })
    },
    updateSlaveHandle(row) {
      this.slave.visible = true
      this.slave.status = 'show'
      this.slave.temp = {
        id: row.id,
        ip: row.ip,
        slave_name: row.slave_name,
        mark: row.mark,
        parallel_max: row.parallel_max,
        parallel_now: row.parallel_now,
        work_path: row.work_path,
        status: row.status
      }
    },
    editSlave() {
      this.$refs.dataForm.validate((validate) => {
        if (validate) {
          editSlaveInfo(this.slave.temp).then(response => {
            this.$message.success('更新成功')
            this.slave.visible = false
            this.getDataSlaveInfo()
          })
        }
      })
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 导出
    exportExcelHandle() {
      const tHeader = ['ID', '节点名称', 'IP', '用户名', '最大线程', '当前线程', '状态', '工作目录', '备注']// 上面设置Excel的表格第一行的标题
      const filterVal = ['id', 'slave_name', 'ip', 'user_name', 'parallel_max', 'parallel_now', 'status', 'work_path', 'mark'] // 上面的index、nickName、name是tableData里对象的属性
      const tableData = this.tableData // 把data里的tableData存到list
      const excelName = '执行机'
      exportExcel1(tHeader, filterVal, tableData, excelName)
    },
    batchHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      if (key === 'cancelManager') {
        this.cancelManager()
      }
      if (key === 'addManager') {
        this.addManager()
      }
    },
    cancelManager() {
      let failCount = 0
      const self = this
      this.$confirm('确认取消管理选中的' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.selectIds.forEach(function(val) {
          console.log({ id: val })
          delExecutor({ id: val }).then(response => {
          }).catch(() => {
            failCount++
          })
        })
        const intervalId = setInterval(function() {
          clearInterval(intervalId)
          self.getDataSlaveInfo()
          if (failCount === 0) {
            self.$notify({
              title: '通知',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            self.$notify({
              title: '通知',
              message: '共' + failCount + '条数据删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }, 300)
      }).catch()
    },
    addManager() {
      let failCount = 0
      const self = this
      this.$confirm('确认添加管理选中的' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.selectIds.forEach(function(val) {
          addExecutor({ id: val }).then(response => {
          }).catch(() => {
            failCount++
          })
        })
        const intervalId = setInterval(function() {
          clearInterval(intervalId)
          self.getDataSlaveInfo()
          if (failCount === 0) {
            self.$notify({
              title: '通知',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          } else {
            self.$notify({
              title: '通知',
              message: '共' + failCount + '条数据添加失败',
              type: 'error',
              duration: 2000
            })
          }
        }, 300)
      }).catch()
    }
  }
}
</script>

<style scoped>

  .slave-label-name .el-input{
    width: 262px;
  }
  .slave-label-name .el-textarea{
    width: 262px;
  }
  .dialog-main {
      height: 410px;
      overflow-y: auto;
  }

  .btn {
    float: right;
  }

  .btn:nth-child(2) {
    margin-right: 20px;
  }

  .export {
    float: right;
  }

  .filter-container {
    margin-bottom: 10px;
  }

  .filter-item {
    margin-bottom: 0px;
  }

</style>
